package com.example.xinlijiankangsys.Interceptor;

import com.example.xinlijiankangsys.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.server.HandshakeInterceptor;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class CustomHandshakeInterceptor implements HandshakeInterceptor {
    @Autowired
    private  UserService userService;
    private static final org.slf4j.Logger log
            = org.slf4j.LoggerFactory.getLogger(CustomHandshakeInterceptor.class);
    @Autowired
    public CustomHandshakeInterceptor(UserService userService) {
        this.userService= userService;
    }

    public static final List<String> REQUIRED_QUERY_PARAMS = List.of("id");
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        //获取ws携带的登录的用户id
        // 获取查询参数
        String queryParams = request.getURI().getQuery();
        // 解析参数
        Map<String,String> map=parseQueryParams(queryParams);
        //随便判断一下id是否存在
        log.info("第一次握手连接的用户id为:"+map);
        // 如果验证通过，可以将参数存储在 attributes 中
        attributes.put("identityMsg",map);
        return map.get("id")!=null&& userService.isUserExist(map.get("id")); // 允许握手
    }
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }

    public  Map<String, String> parseQueryParams(String queryParams) {
        Map<String, String> paramMap = new HashMap<>();
        if (queryParams != null) {
            String[] pairs = queryParams.split("&");
            for (String pair : pairs) {
                String[] keyValue = pair.split("=");
                if (keyValue.length == 2) {
                    //key
                    String key = keyValue[0];
                    if(!paramMap.containsKey(key)) {//如果不存在这个key
                        for (String requiredQueryParam : REQUIRED_QUERY_PARAMS) {
                            if (requiredQueryParam.equals(key)) {
                                paramMap.put(key, keyValue[1]);
                                break;
                            }
                        }
                    }

                }
            }
        }
        return paramMap;
    }
}
